import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_deer/account/account_router.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/routers/fluro_navigator.dart';
import 'package:flutter_deer/setting/setting_router.dart';
import 'package:flutter_deer/shop/iview/shop_iview.dart';
import 'package:flutter_deer/shop/models/user_entity.dart';
import 'package:flutter_deer/shop/presenter/shop_presenter.dart';
import 'package:flutter_deer/shop/provider/user_provider.dart';
import 'package:flutter_deer/shop/shop_router.dart';
import 'package:flutter_deer/util/image_utils.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/theme_utils.dart';
import 'package:flutter_deer/widgets/fadein_text.dart';
import 'package:flutter_deer/widgets/load_image.dart';
import 'package:flutter_deer/widgets/state_layout.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:provider/provider.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:wave/config.dart';
import 'package:wave/wave.dart';

class ShopPage extends StatefulWidget {

  const ShopPage({
    super.key,
    this.isAccessibilityTest = false,
  });

  final bool isAccessibilityTest;
  
  @override
  _ShopPageState createState() => _ShopPageState();
}

class _ShopPageState extends State<ShopPage> with BasePageMixin<ShopPage, ShopPagePresenter>, AutomaticKeepAliveClientMixin<ShopPage> implements ShopIMvpView {
  
  List<String> _menuTitle = [];
  final List<String> _menuImage = ['zhls', 'zjgl', 'zjzh', 'czgl','cz'];
  final List<String> _menuDarkImage = ['zhls_dark', 'zjgl_dark', 'zjzh_dark', 'czgl_dark','cz_dark'];

  UserProvider provider = UserProvider();

  @override
  void initState() {
    super.initState();
  }

  @override
  void setUser(UserInfoEntity? user) {
    provider.setUser(user);
  }

  @override
  void setAgentUser(bool? flag){
    provider.setAgentUser(flag);
  }

  @override
  bool get isAccessibilityTest => widget.isAccessibilityTest;

  static const _colors = [
    Colours.dark_button_disabled,
    Colours.gradient_blue,
  ];

  static const _heightPercentages = [
    0.65,
    0.66,
  ];
  
  @override
  Widget build(BuildContext context) {
    super.build(context);
    final Color? iconColor = ThemeUtils.getIconColor(context);
    _menuTitle = ['${DeerLocalizations.of(context)!.accountStatement.nullSafe}', '${DeerLocalizations.of(context)!.fundManagement.nullSafe}', '${DeerLocalizations.of(context)!.withdrawalAccount.nullSafe}', '${DeerLocalizations.of(context)!.rechargeRecord.nullSafe}','${DeerLocalizations.of(context)!.recharge.nullSafe}'];
    final Widget line = Container(
      height: 6,
      width: MediaQuery.of(context).size.width,
      margin: const EdgeInsets.only(left: 0.0,right: 0.0),
      color: context.isDark?Colors.transparent:Colours.unselected_item_color,
      child: context.isDark?Gaps.line:Visibility(visible: false,child: Row(),),
    );
    return ChangeNotifierProvider<UserProvider>(
      create: (_) => provider,
      child: Scaffold(
        // backgroundColor
        appBar: AppBar(
          backgroundColor: context.isDark?Colors.transparent:Colours.app_main,
          actions: <Widget>[
            // IconButton(
            //   tooltip: '消息',
            //   onPressed: () {
            //     NavigatorUtils.push(context, ShopRouter.messagePage);
            //   },
            //   icon: LoadAssetImage(
            //     'shop/message',
            //     key: const Key('message'),
            //     width: 24.0,
            //     height: 24.0,
            //     color: iconColor,
            //   ),
            // ),
            IconButton(
              tooltip: '${DeerLocalizations.of(context)!.setUp.nullSafe}',
              onPressed: () {
                NavigatorUtils.pushResult(context, SettingRouter.settingPage,(result){
                  if(provider.user!=null&&provider.user!.sysUser!=null&&SpUtil.containsKey(Constant.tempUserAvatarUrl)==true&&SpUtil.getString(Constant.tempUserAvatarUrl)!=provider.user!.sysUser!.avatar!.nullSafe) {
                    this.initState();
                  }
                });
              },
              icon: LoadAssetImage(
                'shop/setting',
                key: const Key('setting'),
                width: 24.0,
                height: 24.0,
                color: iconColor,
              ),
            )
          ],
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Stack(
              children: [
                Container(
                  width: MediaQuery.of(context).size.width,
                  height: context.isDark?0:120,
                  child: Visibility(
                    visible: !context.isDark,
                    child: WaveWidget(
                        config: CustomConfig(
                          colors: _colors,
                          durations: [10000, 8000,],
                          heightPercentages: _heightPercentages,
                        ),
                        backgroundColor: Colours.app_main,
                        size: Size(double.infinity, double.infinity),
                        waveAmplitude: 0
                    ),
                  )
                ),
                Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Gaps.vGap12,
                      Consumer<UserProvider>(
                        builder: (_, provider, child) {
                          final Widget header = Stack(
                            children: <Widget>[
                              const SizedBox(width: double.infinity, height: 56.0),
                              Consumer<UserProvider>(
                                builder: (_, provider, child) {
                                  if(provider.stateType==StateType.loading){
                                    return LoadingAnimationWidget.horizontalRotatingDots(color: context.isDark ? Colors.white : Colors.white,size: 50);
                                  }
                                  return Text('${provider.user!.sysUser!.username.nullSafe}');
                                }
                              ),
                              Text(
                                '',
                                style: TextStyles.textBold24,
                              ),
                              Positioned(
                                right: 0.0,
                                child: provider.stateType==StateType.loading?LoadingAnimationWidget.dotsTriangle(
                                  color: context.isDark ? Colors.white : Colors.white,
                                  size: 50,
                                ):CircleAvatar(
                                  radius: 28.0,
                                  backgroundColor: Colors.transparent,
                                  backgroundImage: ImageUtils.getImageProvider(Constant.imageServerHost+'${provider.user!.sysUser!.avatar.nullSafe}', holderImg: 'shop/tx'),
                                ),
                              ),
                              child!,
                            ],
                          );
                          return Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 16.0),
                            child: MergeSemantics(
                              child: header,
                            ),
                          );
                        },
                        child: Positioned(
                          top: 38.0,
                          left: 0.0,
                          child: Row(
                            children: <Widget>[
                              LoadAssetImage('vip', width: 40.0, height: 16.0,),
                              Consumer<UserProvider>(
                                  builder: (_, provider, child) {
                                    return  Text(provider.stateType==StateType.loading?'${DeerLocalizations.of(context)!.playerAccount.nullSafe}: -- ':'${DeerLocalizations.of(context)!.playerAccount.nullSafe}:${provider.user?.sysUser?.accountId.nullSafe}', style: TextStyles.textSize12);
                                  }),

                              Gaps.hGap8,
                              Gaps.hGap8,
                              Consumer<UserProvider>(
                                  builder: (_, provider, child) {
                                    if(provider.stateType==StateType.loading){
                                      return Text('${DeerLocalizations.of(context)!.invitationCode.nullSafe}:--', style: TextStyles.textSize12);
                                    }
                                    return Text(provider.stateType==StateType.loading?'${DeerLocalizations.of(context)!.invitationCode.nullSafe}: -- ':'${DeerLocalizations.of(context)!.invitationCode.nullSafe}:${provider.user?.sysUser?.shareCode.nullSafe}',style: TextStyles.textSize12);
                                  }),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                )
              ],
            ),
            Visibility(visible: context.isDark,child: Gaps.vGap24,),
            line,
            Gaps.vGap24,
            MergeSemantics(
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  '${DeerLocalizations.of(context)!.account.nullSafe}',
                  style: TextStyles.textBold18,
                ),
              ),
            ),
            _ShopFunctionModule(
              data: _menuTitle,
              image: _menuImage,
              darkImage: _menuDarkImage,
              onItemClick: (index) {
                if (index == 0) {
                  NavigatorUtils.push(context, AccountRouter.accountRecordListPage);
                } else if (index == 1) {
                  NavigatorUtils.push(context, AccountRouter.accountPage);
                } else if (index == 2) {
                  NavigatorUtils.push(context, AccountRouter.withdrawalAccountPage);
                } else if (index == 3) {
                  NavigatorUtils.push(context, AccountRouter.rechargeManagePage);
                } else if (index == 4) {
                  NavigatorUtils.push(context, AccountRouter.addRechargePage);
                }
              },
            ),
            line,
            Gaps.vGap24,
            MergeSemantics(
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  '${DeerLocalizations.of(context)!.agent.nullSafe}',
                  style: TextStyles.textBold18,
                ),
              ),
            ),
            /// 使用Flexible防止溢出
            Flexible(
              child:  Consumer<UserProvider>(
    builder: (_, provider, child) {
      if(provider.agentUser==true){
        return _ShopFunctionModule(
              data: ['${DeerLocalizations.of(context)!.subordinate.nullSafe}','${DeerLocalizations.of(context)!.rechargeRecord.nullSafe}','${DeerLocalizations.of(context)!.withdrawRecord.nullSafe}','${DeerLocalizations.of(context)!.bettingRecord.nullSafe}'],
              image: const ['agent','sf','xf','tzjl'],
              darkImage: const ['agent_dark','sf_dark','xf_dark','tzjl_dark'],
              onItemClick: (index) {
                if(index==0){
                  NavigatorUtils.push(context, ShopRouter.agentListPage,arguments: provider.agentUser??false);
                }else if(index==1){
                  NavigatorUtils.push(context, ShopRouter.depositScoreListPage);
                }else if(index==2){
                  NavigatorUtils.push(context, ShopRouter.takeOutScoreListPage);
                }else if(index==3){
                  NavigatorUtils.push(context, ShopRouter.agentBettingRecordPage);
                }else{
                  NavigatorUtils.push(context, ShopRouter.shopSettingPage);
                }
              },
            );
      }else{
        return _ShopFunctionModule(
          data: ['${DeerLocalizations.of(context)!.subordinate.nullSafe}'],
          image: const ['agent'],
          darkImage: const ['agent_dark'],
          onItemClick: (index) {
            if(index==0){
              NavigatorUtils.push(context, ShopRouter.agentListPage,arguments: provider.agentUser??false);
            }else{
              NavigatorUtils.push(context, ShopRouter.shopSettingPage);
            }
          },
        );
      }
    })
            ),
          ],
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => false;

  @override
  ShopPagePresenter createPresenter() => ShopPagePresenter();
 
}

class _ShopFunctionModule extends StatelessWidget {

  const _ShopFunctionModule({
    required this.onItemClick,
    required this.data,
    required this.image,
    required this.darkImage,
  });
  
  final Function(int index) onItemClick;
  final List<String> data;
  final List<String> image;
  final List<String> darkImage;
  
  @override
  Widget build(BuildContext context) {
    double textWidth = 0;
    for(int i=0;i<data.length;i++){
      TextPainter textPainter = TextPainter(
        text: TextSpan(
          text: data.elementAt(i),
        ),
        textDirection: TextDirection.ltr,
      );
      textPainter.layout();
      if(textWidth<textPainter.size.width){
        textWidth = textPainter.size.width;
      }
    }
    int crossAxisCount = 4;
    if(textWidth>MediaQuery.of(context).size.width/4-40){
      crossAxisCount = 3;
    }
    return AnimationLimiter(child:
    GridView.builder(
      shrinkWrap: true,
      padding: EdgeInsets.fromLTRB(8.0, 0, 8.0, 12.0),
      physics: NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: crossAxisCount,
        childAspectRatio: 1.18,
      ),
      itemCount: data.length,
      itemBuilder: (_, index) {
        return AnimationConfiguration.staggeredGrid(
          position: index,
          duration: Duration(milliseconds: 500),
          columnCount: 4,
          child: ScaleAnimation(
            child: FadeInAnimation(
              child: InkWell(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    LoadAssetImage(context.isDark ? 'shop/${darkImage[index]}' : 'shop/${image[index]}', width: 32.0),
                    Gaps.vGap4,
                    FadeInText(
                      text: data[index],
                      // style: TextStyles.textSize12,
                    )
                  ],
                ),
                onTap: () {
                  onItemClick(index);
                },
              )
            ),
          ),
        );
      },
    )
    );
  }
}
